package cn.edu.guet.tts.controller;

import cn.edu.guet.tts.common.Result;
import cn.edu.guet.tts.entity.TbOrder;
import cn.edu.guet.tts.service.ITbOrderService;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import cn.edu.guet.tts.entity.TbTicket;
import cn.edu.guet.tts.service.ITbTicketService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;
import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

import cn.edu.guet.tts.service.ITbTrainService;
import cn.edu.guet.tts.entity.TbTrain;

import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 * 车次管理表 前端控制器
 * </p>
 *
 * @author test
 * @since 
 */
@RestController
@RequestMapping("/tbTrain")
public class TbTrainController {

    private static final Logger log = LoggerFactory.getLogger(TbTrainController.class);
    @Resource
    private ITbTrainService tbTrainService;

    @Resource
    private ITbTicketService tbTicketService;
    @Resource
    private ITbOrderService tbOrderService;

    /**
     * 新增或者更新
     * @param tbTrain
     * @return
     */
    @PostMapping
    public Result save(@RequestBody TbTrain tbTrain) {
        boolean isNew = tbTrain.getId() == null;

        // 保存车次信息，MyBatis Plus 会自动获取自增的 ID
        log.info("新增或更新数据：{}", tbTrain);
        tbTrainService.saveOrUpdate(tbTrain);

        if (isNew) {
            // 获取新增车次的ID
            Integer trainId = tbTrain.getId();

            // 批量插入车票数据
            List<TbTicket> ticketList = new ArrayList<>();
            for (int carriage = 1; carriage <= 5; carriage++) {
                for (int row = 1; row <= 5; row++) {
                    for (char seat = 'A'; seat <= 'E'; seat++) {
                        TbTicket ticket = new TbTicket();
                        ticket.setTrainId(trainId);
                        ticket.setCarriageNumber(carriage);
                        ticket.setSeatNumber(row + String.valueOf(seat));
                        ticket.setTicketStatus("未售出");
                        ticketList.add(ticket);
                    }
                }
            }
            // 批量插入车票
            tbTicketService.saveBatch(ticketList);
        }

        return Result.success();
    }

    /**
     * 根据车次id删除
     * @param id
     * @return
     */
    @Transactional
    @DeleteMapping("/{id}")
    public Result delete(@PathVariable Integer id) {
        log.info("级联删除车票");
        tbTicketService.deleteByTrainId(id);
        log.info("级联删除拥有该车次车票的订单");
        QueryWrapper<TbOrder> orderQueryWrapper = new QueryWrapper<>();
        orderQueryWrapper.eq("train_id", id);
        tbOrderService.remove(orderQueryWrapper);
        log.info("删除车次：{}",id);
        return Result.success(tbTrainService.removeById(id));
    }


    /**
     * 根据车次id批量删除
     * @param ids
     * @return
     */
    @PostMapping("/del/batch")
    public Result deleteBatch(@RequestBody List<Integer> ids) {
        // 级联删除车次车票和订单
        log.info("根据车次id批量删除车票和订单");
        ids.forEach(id -> {
            tbTicketService.deleteByTrainId(id);
            QueryWrapper<TbOrder> orderQueryWrapper = new QueryWrapper<>();
            orderQueryWrapper.eq("train_id", id);
            tbOrderService.remove(orderQueryWrapper);
        });
        log.info("批量删除车次");
        return Result.success(tbTrainService.removeByIds(ids));
    }

    /**
     * 查询全部
     * @return
     */
    @GetMapping
    public Result findAll() {
        return Result.success(tbTrainService.list());
    }

    /**
     * 根据id查询
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Result findOne(@PathVariable Integer id) {
        return Result.success(tbTrainService.getById(id));
    }

    /**
     * 分页
     * @param name
     * @param pageNum
     * @param pageSize
     * @return
     */
    @GetMapping("/page")
    public Result findPage(@RequestParam(defaultValue = "") String name,
                           @RequestParam Integer pageNum,
                           @RequestParam Integer pageSize) {
        QueryWrapper<TbTrain> queryWrapper = new QueryWrapper<>();
        queryWrapper.orderByDesc("id");
        if (!"".equals(name)) {
            queryWrapper.like("start_station", name).or().like("end_station", name);
        }
        return Result.success(tbTrainService.page(new Page<>(pageNum, pageSize), queryWrapper));
    }


}

